package dao

import (
	"errors"
	__ "order_srv/basic/orderproto"
	"order_srv/handler/models"
)

// 创建围栏
func CreateFence(in *__.CreateFenceReq) (*models.Fence, error) {
	var err error
	//查看用户权限是否足够
	var user models.User
	if err = user.GetUserById(); err != nil {
		return nil, errors.New("查询用户失败")
	}
	if user.Id == 3 {
		return nil, errors.New("用户不权限不足")
	}
	//查询城市是否存在
	var city models.City
	if in.CityId > 0 {
		city.Id = uint32(in.CityId)
	}
	if err = city.GetCity(); err != nil {
		return nil, errors.New("查询城市失败")
	}
	if city.Id == 0 {
		return nil, errors.New("城市不存在")
	}
	//创建围栏
	var fence models.Fence
	fence = models.Fence{
		UserId:      int32(in.UserId),
		CityId:      int32(in.CityId),
		Name:        in.Name,
		Type:        int32(in.Type),
		Latitude:    float64(in.Latitude),
		Longitude:   float64(in.Longitude),
		Coordinates: in.Coordinates,
		Description: in.Description,
		Status:      int32(in.Status),
	}
	if err = fence.CreateFancy(); err != nil {
		return nil, errors.New("创建围栏失败")
	}
	return &fence, err
}

// 修改围栏
func UpdateFence(in *__.UpdateFenceReq) (*models.Fence, error) {
	var err error
	//查看用户权限是否足够
	var user models.User
	if err = user.GetUserById(); err != nil {
		return nil, errors.New("查询用户失败")
	}
	if user.Id == 3 {
		return nil, errors.New("用户不权限不足")
	}
	//查看围栏是否存在
	var fence models.Fence
	if err = fence.GetFenceById(int32(in.Id)); err != nil {
		return nil, errors.New("查询围栏失败")
	}
	if fence.Id == 0 {
		return nil, errors.New("围栏不存在")
	}
	//修改围栏
	fence = models.Fence{
		Id:     uint32(in.Id),
		UserId: int32(in.UserId),
		Status: int32(in.Status),
	}
	if err = fence.UpdateFence(int32(in.Id)); err != nil {
		return nil, errors.New("修改围栏失败")
	}
	return &fence, err
}

// 删除围栏
func DeletedFence(in *__.DeletedFenceReq) (*models.Fence, error) {
	var err error
	//查看用户权限是否足够
	var user models.User
	if err = user.GetUserById(); err != nil {
		return nil, errors.New("查询用户失败")
	}
	if user.Id == 3 {
		return nil, errors.New("用户不权限不足")
	}
	//查看围栏是否存在
	var fence models.Fence
	if err = fence.GetFenceById(int32(in.Id)); err != nil {
		return nil, errors.New("查询围栏失败")
	}
	if fence.Id == 0 {
		return nil, errors.New("围栏不存在")
	}
	//删除围栏
	fence = models.Fence{
		Id:     uint32(in.Id),
		UserId: int32(in.UserId),
	}
	if err = fence.DeleteFence(int32(in.Id)); err != nil {
		return nil, errors.New("删除围栏失败")
	}
	return &fence, err
}

// 列表围栏
func ListFence(in *__.ListFenceReq) ([]*__.ListFence, error) {
	var err error
	var fence models.Fence
	listFence, err := fence.ListFence()
	if err != nil {
		return nil, errors.New("查询围栏列表失败")
	}
	var faceList []*__.ListFence
	for _, r := range listFence {
		faceList = append(faceList, &__.ListFence{
			Id:     int64(r.Id),
			Name:   r.Name,
			Status: int64(r.Status),
			City:   r.City,
			Type:   int64(r.Type),
		})
	}
	return faceList, nil
}
